$(document).ready(function() {

    // --- Toast Notification Handler ---
    const toastEl = document.getElementById('liveToast');
    const toast = new bootstrap.Toast(toastEl);

    function showToast(message, isError = false) {
        const toastBody = toastEl.querySelector('.toast-body');
        toastBody.textContent = message;
        if (isError) {
            toastEl.classList.add('bg-danger', 'text-white');
            toastEl.classList.remove('bg-success');
        } else {
            toastEl.classList.add('bg-success', 'text-white');
            toastEl.classList.remove('bg-danger');
        }
        toast.show();
    }

    // --- Form Auto-Save to localStorage ---
    const form = $('#application-form');
    const formFields = form.find('select, textarea');
    const draftKey = 'application_draft';

    // Load draft from localStorage
    function loadDraft() {
        const draft = localStorage.getItem(draftKey);
        if (draft) {
            const data = JSON.parse(draft);
            if (confirm('检测到有未提交的草稿，是否恢复？')) {
                $('#relation').val(data.relation);
                $('#reason').val(data.reason);
            }
        }
    }

    // Save draft to localStorage
    formFields.on('input', function() {
        const data = {
            relation: $('#relation').val(),
            reason: $('#reason').val(),
        };
        localStorage.setItem(draftKey, JSON.stringify(data));
    });

    // --- Form Submission Handler ---
    form.on('submit', function(e) {
        e.preventDefault();
        
        const submitBtn = $(this).find('button[type="submit"]');
        const spinner = submitBtn.find('.spinner-border');

        // Show spinner and disable button
        submitBtn.prop('disabled', true);
        spinner.removeClass('d-none');

        const formData = new FormData(this);

        $.ajax({
            url: '/api/submit',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                const res = JSON.parse(response);
                if (res.code === 0) {
                    showToast('申请提交成功！');
                    // Clear form and local storage
                    form[0].reset();
                    localStorage.removeItem(draftKey);
                } else {
                    showToast(res.message || '发生未知错误', true);
                }
            },
            error: function(jqXHR) {
                let errorMessage = '提交失败，请检查网络或联系管理员。';
                if (jqXHR.responseJSON && jqXHR.responseJSON.message) {
                    errorMessage = jqXHR.responseJSON.message;
                } else if (jqXHR.responseText) {
                    try {
                       const err = JSON.parse(jqXHR.responseText);
                       errorMessage = err.message;
                    } catch(e) {/* ignore */}
                }
                showToast(errorMessage, true);
            },
            complete: function() {
                // Hide spinner and enable button
                submitBtn.prop('disabled', false);
                spinner.addClass('d-none');
            }
        });
    });
    
    // Initial draft load
    loadDraft();
}); 